import React, { useContext, useReducer } from 'react'
import { Button } from 'antd';

const reducer = (prevState, action) => {
    let newState = { ...prevState }
    if (action.type === 2) {
        newState.a = action.value
        newState.aColor = action.color
        return newState
    }
    if (action.type === 3) {
        newState.b = action.value
        newState.bColor = action.color
        return newState
    }
    return prevState
}

const initialState = {
    a: "22222",
    aColor: "yellow",
    b: "33333",
    bColor: "blue"
}
var GlobalContext = React.createContext()

function App() {
    const [state, dispatch] = useReducer(reducer, initialState)
    return (
        <GlobalContext.Provider value={{
            state,
            dispatch
        }}>
            <div>
                <Child1 />
                <Child2 />
                <Child3 />
            </div>
        </GlobalContext.Provider>
    )
}

function Child1() {
    const { dispatch } = useContext(GlobalContext)
    return (
        <div>
            <Button type="primary" onClick={() => {
                dispatch({
                    type: 2,
                    value: "2222-change",
                    color: "green"
                })
            }}>修改2</Button>
            <Button type="primary" onClick={() => {
                dispatch({
                    type: 3,
                    value: "2222-change",
                    color: "red"
                })
            }}>修改3</Button>
        </div>
    )
}

function Child2() {
    const { state } = useContext(GlobalContext)
    return (
        <div style={{ background: state.aColor, height: "100px" }}>
            Child2-{state.a}
        </div>
    )
}

function Child3() {
    const { state } = useContext(GlobalContext)
    return (
        <div style={{ background: state.bColor, height: "100px" }}>
            Child3-{state.b}
        </div>
    )
}

export default App